/**
 * DEPENDENCIAS:
 * modulo meusCRUD.js
 * modulo meusPopups.js 
 * modulo meusGerenciamentoDeErros.js
 * 
 * FUNCIONALIDADE:
 * Funcoes que montam formularios em formato Wizard
 * 
 *  TODO:
 *  melhorar funcoes, generalizar wizard e wizard update passando mais parametros
 *  como nome dos botoes 
 *  funcao de popular
 *  funcao de persistencia
 *  
 *  melhorar funcao de wizard update file, passando mais parametros
 *  como mensagem de sucesso
 */

/*
monta datagrid sem nenhum tipo de controle ou filtro, apenas a tabela.
 */
function dataGridSimples(id, arrString){
	var aoColumns = $.parseJSON(arrString);
	for(var i=0; i< aoColumns.length; i++){
		if(aoColumns[i].fnRender!=undefined){
			eval("var func = " + aoColumns[i].fnRender);
			aoColumns[i].fnRender = func;
		}
	}
	var possuiHtmlControl=false;
	for (var i = 0; i < aoColumns.length; i++) {
		if(aoColumns[i].mDataProp=="htmlControl"){
			possuiHtmlControl=true;
		}
	}
	if(!possuiHtmlControl){
		var htmlControl = {"sTitle": "Opções", "mDataProp": "htmlControl","bSortable": false, "bVisible": true, "sWidth": "45px","sDefaultContent":"", 
				"fnRender": function ( oObj ) {
					return  "<button type=\"button\"  id=\"deletarBtn_"+oObj.aData.id+"\"   class=\"deletarBtn"+id+"\" onclick=\"deletarDaTela(event,'"+id+"')\">Deletar</button>";
				}
		};
		aoColumns.push(htmlControl);
	}
	options ={
			"sDom": ' t ',
			"bStateSave": false,
			"bDeferRender":true,
			"bProcessing":false,
			"bJQueryUI" : true,
			"bFilter":false,
			"bLengthChange":false,
			"bSort": false,
			"bInfo": false,
			"bPaginate":false,
			"oLanguage": {
				"sProcessing": "Por favor, espere ...",
				"sLengthMenu": "Mostrar _MENU_ linhas",
				"sZeroRecords": "Não há informações disponíveis.",
				"sInfo": "_START_ até _END_ de _TOTAL_ linhas",
				"sInfoEmpty": "0 até 0 de 0 linhas",
				////"sInfoFiltered": "(filtrado para _MAX_ linhas)", 					
				"sInfoFiltered": "",
				"sInfoPostFix": "",
				"sSearch": "Procurar",
				"sUrl": "",
				"oPaginate": {
					"sFirst": 	 "Primeiro",
					"sPrevious": "Anterior",
					"sNext":     "Próximo",
					"sLast":     "Último"
				}
			},
			"aoColumns": [],
			"fnPreDrawCallback": function( oSettings ) {
				$("#"+id+"_wrapper").css({"min-height": "0px"});
			},
			"fnDrawCallback":function(){
				$(".editarBtn"+id).button({icons: {primary: "ui-icon-pencil"}, text: false});
				$(".editarBtn"+id).css({'width': '20px', 'height': '20px'});
				$(".deletarBtn"+id).button({icons: {primary: "ui-icon-close"}, text: false});
				$(".deletarBtn"+id).css({'width': '20px', 'height': '20px'});
				$(".checkBtn"+id).button({icons: {primary: "ui-icon-check"}, text: false});
				$(".checkBtn"+id).css({'width': '20px', 'height': '20px'});
				$(".reabrirBtn"+id).button({icons: {primary: "ui-icon-folder-open"}, text: false});
				$(".reabrirBtn"+id).css({'width': '20px', 'height': '20px'});
				$(".magnifierGlassDataGridBtn"+id).button({icons: {primary: "ui-icon-search"}, text: false});
				$(".magnifierGlassDataGridBtn"+id).css({'width': '20px', 'height': '20px'});
				$(".printBtn"+id).button({icons: {primary: "ui-icon-print"}, text: false});
				$(".printBtn"+id).css({'width': '20px', 'height': '20px'});
				$('#'+id).highlight('td','highlightEscuro','mouseover', 'mouseout');
				$('#'+id).highlight('tr','highlightEscuro','mouseover', 'mouseout');
			},
			"fnRowCallback": function( nRow, aData, iDisplayIndex ) {

				$(nRow).click(function(event) {
					if ( $(nRow).hasClass('row_selected') )
						$(nRow).removeClass('row_selected');
					else
						$(nRow).addClass('row_selected');
				});
				return nRow;
			}
	}; 
	options.aoColumns=aoColumns;
	$('#'+id).dataTable(options);
	$('#'+id).css({'width': '100%'});
}

/*
monta datagrid com controles de selecionar todos, selecionar nenhum e excluir todos selecionados
 */
function oneToMany(id, arrString){
	var aoColumns = $.parseJSON(arrString);
	for(var i=0; i< aoColumns.length; i++){
		if(aoColumns[i].fnRender!=undefined){
			eval("var func = " + aoColumns[i].fnRender);
			aoColumns[i].fnRender = func;
		}
	}
	var possuiHtmlControl=false;
	for (var i = 0; i < aoColumns.length; i++) {
		if(aoColumns[i].mDataProp=="htmlControl"){
			possuiHtmlControl=true;
		}
	}
	if(!possuiHtmlControl){
		var htmlControl = {"sTitle": "Opções", "mDataProp": "htmlControl","bSortable": false, "bVisible": true, "sWidth": "45px","sDefaultContent":"", 
				"fnRender": function ( oObj ) {
					return  "<button type=\"button\" id=\"deletarBtn_"+oObj.aData.id+"\"   class=\"deletarBtn"+id+"\" onclick=\"deletarDaTela(event,'"+id+"')\">Deletar</button>";
				}
		};
		aoColumns.push(htmlControl);
	}
	var options ={
			//"sDom": '<"H" <"#'+id+'_controle" > > t ',
			"sDom": 'Rl<"H"fr>t<"F"ip>S',
			"bStateSave": false,
			"bDeferRender":true,
			"bProcessing":false,
			"bJQueryUI" : true,
			"bFilter":false,
			"bLengthChange":false,
			"bSort": false,
			"bInfo": false,
			"bPaginate":false,
			"oLanguage": {
				"sProcessing": "Por favor, espere ...",
				"sLengthMenu": "Mostrar _MENU_ linhas",
				"sZeroRecords": "Não há informações disponíveis.",
				"sInfo": "_START_ até _END_ de _TOTAL_ linhas",
				"sInfoEmpty": "0 até 0 de 0 linhas",
				////"sInfoFiltered": "(filtrado para _MAX_ linhas)", 					
				"sInfoFiltered": "",
				"sInfoPostFix": "",
				"sSearch": "Procurar",
				"sUrl": "",
				"oPaginate": {
					"sFirst": 	 "Primeiro",
					"sPrevious": "Anterior",
					"sNext":     "Próximo",
					"sLast":     "Último"
				}
			},
			"oColVis": {
				"buttonText": "&nbsp;⬇",
				"bRestore": true,
				"sAlign": "left"
			},
			"sScrollY": "200px",
			"aoColumns": [],
			"fnPreDrawCallback": function( oSettings ) {
				$("#"+id+"_wrapper").css({"min-height": "0px"});
			},
			"fnDrawCallback":function(){
				$(".editarBtn"+id).button({icons: {primary: "ui-icon-pencil"}, text: false});
				$(".editarBtn"+id).css({'width': '20px', 'height': '20px'});
				$(".deletarBtn"+id).button({icons: {primary: "ui-icon-close"}, text: false});
				$(".deletarBtn"+id).css({'width': '20px', 'height': '20px'});
				$(".magnifierGlassDataGridBtn"+id).button({icons: {primary: "ui-icon-search"}, text: false});
				$(".magnifierGlassDataGridBtn"+id).css({'width': '20px', 'height': '20px'});
				$(".printBtn"+id).button({icons: {primary: "ui-icon-print"}, text: false});
				$(".printBtn"+id).css({'width': '20px', 'height': '20px'});
				$(".alertarBtn"+id).button({icons: {primary: "ui-icon-notice"}, text: false});
				$(".alertarBtn"+id).css({'width': '20px', 'height': '20px'});
				$(".informarBtn"+id).button({icons: {primary: "ui-icon-signal-diag"}, text: false});
				$(".informarBtn"+id).css({'width': '20px', 'height': '20px'});	
				$(".noticiarBtn"+id).button({icons: {primary: "ui-icon-info"}, text: false});
				$(".noticiarBtn"+id).css({'width': '20px', 'height': '20px'});
				
				$('#'+id).highlight('td','highlightEscuro','mouseover', 'mouseout');
				$('#'+id).highlight('tr','highlightEscuro','mouseover', 'mouseout');
			},
			"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
				$(nRow).click(function(event) {
					if ( $(nRow).hasClass('row_selected') )
						$(nRow).removeClass('row_selected');
					else
						$(nRow).addClass('row_selected');
				});
				return nRow;
			}
	}; 
	options.aoColumns=aoColumns;
	$('#'+id).dataTable(options);
	$('#'+id).css({'width': '100%'});
	$("#"+id+"_controle").append( 
			"<button type=\"button\" class=\"headerTextBtn\" onclick=\"multiDelete('"+id+"',null);\" id=\"deletarMultiBtn"+id+"\">selecionados</button>"+
			"<button type=\"button\" class=\"headerTextBtn\" onclick=\"selectAll('"+id+"');\" id=\"selectAllBtn"+id+"\">todos</button>"+
			"<button type=\"button\" class=\"headerTextBtn\" onclick=\"selectNone('"+id+"');\" id=\"selectNoneBtn"+id+"\">nenhum</button>"
	);
	var deletarMultiBtn = $("#deletarMultiBtn"+id).button({ icons: { primary: "ui-icon ui-icon-closethick"},text: true});
	var selectAllBtn = $("#selectAllBtn"+id).button({ icons: { primary: "ui-icon ui-icon-carat-1-se"},text: true});
	var selectNoneBtn = $("#selectNoneBtn"+id).button({ icons: { primary: "ui-icon ui-icon-carat-1-ne"},text: true});
}

//com tamanho
function oneToManyHeight(id, arrString, height){
	var aoColumns = $.parseJSON(arrString);
	for(var i=0; i< aoColumns.length; i++){
		if(aoColumns[i].fnRender!=undefined){
			eval("var func = " + aoColumns[i].fnRender);
			aoColumns[i].fnRender = func;
		}
	}
	var possuiHtmlControl=false;
	for (var i = 0; i < aoColumns.length; i++) {
		if(aoColumns[i].mDataProp=="htmlControl"){
			possuiHtmlControl=true;
		}
	}
	if(!possuiHtmlControl){
		var htmlControl = {"sTitle": "Opções", "mDataProp": "htmlControl","bSortable": false, "bVisible": true, "sWidth": "45px","sDefaultContent":"", 
				"fnRender": function ( oObj ) {
					return  "<button type=\"button\" id=\"deletarBtn_"+oObj.aData.id+"\"   class=\"deletarBtn"+id+"\" onclick=\"deletarDaTela(event,'"+id+"')\">Deletar</button>";
				}
		};
		aoColumns.push(htmlControl);
	}
	var options ={
			//"sDom": '<"H" <"#'+id+'_controle" > > t ',
			"sDom": 'Rl<"H"fr>t<"F"ip>S',
			"bStateSave": false,
			"bDeferRender":true,
			"bProcessing":false,
			"bJQueryUI" : true,
			"bFilter":false,
			"bLengthChange":false,
			"bSort": false,
			"bInfo": false,
			"bPaginate":false,
			"oLanguage": {
				"sProcessing": "Por favor, espere ...",
				"sLengthMenu": "Mostrar _MENU_ linhas",
				"sZeroRecords": "Não há informações disponíveis.",
				"sInfo": "_START_ até _END_ de _TOTAL_ linhas",
				"sInfoEmpty": "0 até 0 de 0 linhas",
				////"sInfoFiltered": "(filtrado para _MAX_ linhas)", 					
				"sInfoFiltered": "",
				"sInfoPostFix": "",
				"sSearch": "Procurar",
				"sUrl": "",
				"oPaginate": {
					"sFirst": 	 "Primeiro",
					"sPrevious": "Anterior",
					"sNext":     "Próximo",
					"sLast":     "Último"
				}
			},
			"oColVis": {
				"buttonText": "&nbsp;⬇",
				"bRestore": true,
				"sAlign": "left"
			},
			"sScrollY": height+"px",
			"aoColumns": [],
			"fnPreDrawCallback": function( oSettings ) {
				$("#"+id+"_wrapper").css({"min-height": "0px"});
			},
			"fnDrawCallback":function(){
				$(".editarBtn"+id).button({icons: {primary: "ui-icon-pencil"}, text: false});
				$(".editarBtn"+id).css({'width': '20px', 'height': '20px'});
				$(".deletarBtn"+id).button({icons: {primary: "ui-icon-close"}, text: false});
				$(".deletarBtn"+id).css({'width': '20px', 'height': '20px'});
				$(".magnifierGlassDataGridBtn"+id).button({icons: {primary: "ui-icon-search"}, text: false});
				$(".magnifierGlassDataGridBtn"+id).css({'width': '20px', 'height': '20px'});
				$(".printBtn"+id).button({icons: {primary: "ui-icon-print"}, text: false});
				$(".printBtn"+id).css({'width': '20px', 'height': '20px'});
				$(".alertarBtn"+id).button({icons: {primary: "ui-icon-notice"}, text: false});
				$(".alertarBtn"+id).css({'width': '20px', 'height': '20px'});
				$(".informarBtn"+id).button({icons: {primary: "ui-icon-signal-diag"}, text: false});
				$(".informarBtn"+id).css({'width': '20px', 'height': '20px'});	
				$(".noticiarBtn"+id).button({icons: {primary: "ui-icon-info"}, text: false});
				$(".noticiarBtn"+id).css({'width': '20px', 'height': '20px'});
				
				$('#'+id).highlight('td','highlightEscuro','mouseover', 'mouseout');
				$('#'+id).highlight('tr','highlightEscuro','mouseover', 'mouseout');
			},
			"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
				$(nRow).click(function(event) {
					if ( $(nRow).hasClass('row_selected') )
						$(nRow).removeClass('row_selected');
					else
						$(nRow).addClass('row_selected');
				});
				return nRow;
			}
	}; 
	options.aoColumns=aoColumns;
	$('#'+id).dataTable(options);
	$('#'+id).css({'width': '100%'});
	$("#"+id+"_controle").append( 
			"<button type=\"button\" class=\"headerTextBtn\" onclick=\"multiDelete('"+id+"',null);\" id=\"deletarMultiBtn"+id+"\">selecionados</button>"+
			"<button type=\"button\" class=\"headerTextBtn\" onclick=\"selectAll('"+id+"');\" id=\"selectAllBtn"+id+"\">todos</button>"+
			"<button type=\"button\" class=\"headerTextBtn\" onclick=\"selectNone('"+id+"');\" id=\"selectNoneBtn"+id+"\">nenhum</button>"
	);
	var deletarMultiBtn = $("#deletarMultiBtn"+id).button({ icons: { primary: "ui-icon ui-icon-closethick"},text: true});
	var selectAllBtn = $("#selectAllBtn"+id).button({ icons: { primary: "ui-icon ui-icon-carat-1-se"},text: true});
	var selectNoneBtn = $("#selectNoneBtn"+id).button({ icons: { primary: "ui-icon ui-icon-carat-1-ne"},text: true});
}


/*
monta datagrid com controles de arquivo 
 */
function oneToManyFile(id, arrStringFiltro){

	try{
		var aoColumns = $.parseJSON(arrStringFiltro);
		for(var i=0; i< aoColumns.length; i++){
			if(aoColumns[i].fnRender!=undefined){
				eval("var func = " + aoColumns[i].fnRender);
				aoColumns[i].fnRender = func;
			}
		}
		var possuiHtmlControl=false;
		for (var i = 0; i < aoColumns.length; i++) {
			if(aoColumns[i].mDataProp=="htmlControl"){
				possuiHtmlControl=true;
			}
		}
		if(!possuiHtmlControl){
			var htmlControl = {"sTitle": "Opções", "mDataProp": "htmlControl","bSortable": false, "bVisible": true, "sWidth": "45px","sDefaultContent":"", 
					"fnRender": function ( oObj ) {
						if(oObj.aData.arquivo.id!=null){
							return  "<button type=\"button\" id=\"magnifierBtn_"+oObj.aData.id+"\"   class=\"magnifierGlassDataGridBtn"+id+"\" onclick=\"window.open('arquivoes/showdoc/"+oObj.aData.id+"','_blank')\">Ver</button>"+
							"<button type=\"button\" id=\"deletarBtn_"+oObj.aData.id+"\"   class=\"deletarBtn"+id+"\" onclick=\"deletarDaTela(event,'"+id+"')\">Deletar</button>";
						}else{
							return  "<button type=\"button\" id=\"deletarBtn_"+oObj.aData.id+"\"   class=\"deletarBtn"+id+"\" onclick=\"deletarDaTela(event,'"+id+"')\">Deletar</button>";
						}
					}
			};
			aoColumns.push(htmlControl);
		}
		var options ={
				"sDom": '<"H" <"#'+id+'_controle" > > t ',
				"bStateSave": false,
				"bDeferRender":true,
				"bProcessing":false,
				"bJQueryUI" : true,
				"bFilter":false,
				"bLengthChange":false,
				"bSort": false,
				"bInfo": false,
				"bPaginate":false,
				"oLanguage": {
					"sProcessing": "Por favor, espere ...",
					"sLengthMenu": "Mostrar _MENU_ linhas",
					"sZeroRecords": "Não há informações disponíveis.",
					"sInfo": "_START_ até _END_ de _TOTAL_ linhas",
					"sInfoEmpty": "0 até 0 de 0 linhas",
					//"sInfoFiltered": "(filtrado para _MAX_ linhas)", 			
					"sInfoFiltered": "",
					"sInfoPostFix": "",
					"sSearch": "Procurar",
					"sUrl": "",
					"oPaginate": {
						"sFirst": 	 "Primeiro",
						"sPrevious": "Anterior",
						"sNext":     "Próximo",
						"sLast":     "Último"
					}
				},
				"aoColumns": [],
				"fnPreDrawCallback": function( oSettings ) {
					$("#"+id+"_wrapper").css({"min-height": "0px"});
				},
				"fnDrawCallback":function(){
					$(".editarBtn"+id).button({icons: {primary: "ui-icon-pencil"}, text: false});
					$(".editarBtn"+id).css({'width': '20px', 'height': '20px'});
					$(".deletarBtn"+id).button({icons: {primary: "ui-icon-close"}, text: false});
					$(".deletarBtn"+id).css({'width': '20px', 'height': '20px'});
					$(".magnifierGlassDataGridBtn"+id).button({icons: {primary: "ui-icon-search"}, text: false});
					$(".magnifierGlassDataGridBtn"+id).css({'width': '20px', 'height': '20px'});
					$('#'+id).highlight('td','highlightEscuro','mouseover', 'mouseout');
					$('#'+id).highlight('tr','highlightEscuro','mouseover', 'mouseout');
				},
				"fnRowCallback": function( nRow, aData, iDisplayIndex ) {

					$(nRow).click(function(event) {
						if ( $(nRow).hasClass('row_selected') )
							$(nRow).removeClass('row_selected');
						else
							$(nRow).addClass('row_selected');
					});
					return nRow;
				}
		}; 
		options.aoColumns=aoColumns;

		$('#'+id).dataTable(options);
		$('#'+id).css({'width': '100%'});
		$("#"+id+"_controle").append( 
				"<button type=\"button\" class=\"headerTextBtn\" onclick=\"multiDelete('"+id+"',null);\" id=\"deletarMultiBtn"+id+"\">selecionados</button>"+
				"<button type=\"button\" class=\"headerTextBtn\" onclick=\"selectAll('"+id+"');\" id=\"selectAllBtn"+id+"\">todos</button>"+
				"<button type=\"button\" class=\"headerTextBtn\" onclick=\"selectNone('"+id+"');\" id=\"selectNoneBtn"+id+"\">nenhum</button>"
		);
		var deletarMultiBtn = $("#deletarMultiBtn"+id).button({ icons: { primary: "ui-icon ui-icon-closethick"},text: true});
		var selectAllBtn = $("#selectAllBtn"+id).button({ icons: { primary: "ui-icon ui-icon-carat-1-se"},text: true});
		var selectNoneBtn = $("#selectNoneBtn"+id).button({ icons: { primary: "ui-icon ui-icon-carat-1-ne"},text: true});
	}catch(e){alert('Erro')}
}

/*
 * funcao que serializa um formulario e adicona o registro serializado para uma datagrid
 */
function adicionarDoFormParaDatagrid(idForm,idDataGrid){
	var formulario = $("#"+idForm).formParams(false);
	$("#"+idForm + " select").each(function(){
		try{
			eval("formulario."+ idForm+ "."+$(this).attr("name").split("[")[1].split("]")[0]+" = findDataId(formulario."+ idForm+ "."+$(this).attr("name").split("[")[1].split("]")[0]+".id, $(\"#"+$(this).attr("id")+"\").get(0).dataSource);");
			//incluir aqui a limpeza do formulario
		}catch(e){}
	});
	eval("$('#"+idDataGrid+"').dataTable().fnAddData(formulario."+ idForm+ ");");
	$('#'+idDataGrid).dataTable().fnDraw();
	//$("#"+formId).populate(null,{resetForm:true});
}

/*
 * funcao que serializa um formulario com arquivo e adicona o registro serializado para uma datagrid
 */
function adicionarDoFormFileParaDatagrid(idForm,idDataGrid){
	var formulario = $("#"+idForm).formParams(false);
	$("#"+idForm + " select").each(function(){
		try{
			eval("formulario."+ idForm+ "."+$(this).attr("name").split("[")[1].split("]")[0]+" = findDataId(formulario."+ idForm+ "."+$(this).attr("name").split("[")[1].split("]")[0]+".id, $(\"#"+$(this).attr("id")+"\").get(0).dataSource);");
		}catch(e){}
	});
	$("#"+idForm + " input:file").each(function(){
		try{
			eval("formulario."+ idForm+ "."+$(this).attr("name").split("[")[1].split("]")[0]+ ".conteudo = FileAPI.getFiles()[0].file");
		}catch(e){}
	});

	eval("$('#"+idDataGrid+"').dataTable().fnAddData(formulario."+ idForm+ ");");
	$('#'+idDataGrid).dataTable().fnDraw();
}

/*
 * funcao que adiciona o valor de uma combo a um datagrid
 */
function adicionarDoComboParaDatagrid(idCombo,idDataGrid){
	var objFromCombo = findDataId($("#"+idCombo).val() , $("#"+idCombo).get(0).dataSource);
	$('#'+idDataGrid).dataTable().fnAddData(objFromCombo);
	$('#'+idDataGrid).dataTable().fnDraw();
	$('#'+idCombo).val("");
}

/*
 * funcao que remove linhas de uma datatable
 */
function deletarDaTela(event,idDataGrid){
	var clickedTr = selecionarTr(event,idDataGrid);
	if(clickedTr==null){
		clickedTr = $(event.target).parent().parent().parent()[0];
	}
	var aTrs = $('#'+idDataGrid).dataTable().fnSettings().aoData;
	for(var i=0; i< aTrs.length; i++){
		if(aTrs[i].nTr==clickedTr){
			$('#'+idDataGrid).dataTable().fnDeleteRow($('#'+idDataGrid).dataTable().fnGetPosition(clickedTr));
		}
	}
}

/*
 * funcao que remove linhas de uma datatable
 */
function deletarDaTelaCallBack(event,idDataGrid, callBack){
	var clickedTr = selecionarTr(event,idDataGrid);
	if(clickedTr==null){
		clickedTr = $(event.target).parent().parent().parent()[0];
	}
	var aTrs = $('#'+idDataGrid).dataTable().fnSettings().aoData;
	for(var i=0; i< aTrs.length; i++){
		if(aTrs[i].nTr==clickedTr){
			$('#'+idDataGrid).dataTable().fnDeleteRow($('#'+idDataGrid).dataTable().fnGetPosition(clickedTr));
		}
	}
	callBack();
}

/*
 * funcao que monta duas datagrids uma de pesquisa outra de valores selecionados
 */
function multiSelectDataGrid(idDisponiveis,idSelecionadas,comararCom,aoColumnsDisponiveisStr,aoColumnsSelecionadosStr){

	var htmlControlDisponiveis = {"sTitle": "Opções", "mDataProp": "htmlControl","bSortable": false, "bVisible": true, "sWidth": "45px","sDefaultContent":"", 
			"fnRender": function ( oObj ) {
				return  "<button type=\"button\" id=\"addBtn_"+oObj.aData.id+"\"   class=\"addSelecionadosBtn\" onclick=\"addToSelecionados(event,'"+idDisponiveis+"','"+idSelecionadas+"','"+comararCom+"');\" >Passar para direita</button>";
			}
	};
	var htmlControlSelecionadas = {"sTitle": "Opções", "mDataProp": "htmlControl","bSortable": false, "bVisible": true, "sWidth": "45px","sDefaultContent":"", 
			"fnRender": function ( oObj ) {
				return  "<button type=\"button\" id=\"retirarBtn_"+oObj.aData.id+"\"   class=\"voltarDataGridBtn\" onclick=\"deletarDaTela(event,'"+idSelecionadas+"');\">Deletar</button>";
			}
	};

	var aoColumnsDisponiveis = $.parseJSON(aoColumnsDisponiveisStr);
	for(var i=0; i< aoColumnsDisponiveis.length; i++){
		if(aoColumnsDisponiveis[i].fnRender!=undefined){
			eval("var func = " + aoColumnsDisponiveis[i].fnRender);
			aoColumnsDisponiveis[i].fnRender = func;
		}
	}

	var aoColumnsSelecionados = $.parseJSON(aoColumnsSelecionadosStr);
	for(var i=0; i< aoColumnsSelecionados.length; i++){
		if(aoColumnsSelecionados[i].fnRender!=undefined){
			eval("var func = " + aoColumnsSelecionados[i].fnRender);
			aoColumnsSelecionados[i].fnRender = func;
		}
	}

	aoColumnsDisponiveis.push(htmlControlDisponiveis);
	aoColumnsSelecionados.push(htmlControlSelecionadas);

	$('#'+idDisponiveis).dataTable({
		"sDom": 'l<"#filtroesquerda" f>rtip',
		"iDisplayLength": 7,
		"bStateSave": false,
		"bDeferRender": true,
		"bProcessing": false,
		"bJQueryUI" : false,
		"bFilter":true,
		"bLengthChange": false,
		"bSort": false,
		"bInfo": false,
		"bPaginate":false,
		"oLanguage": {
			"sProcessing": "Por favor, espere ...",
			"sLengthMenu": "Mostrar _MENU_ linhas",
			"sZeroRecords": "Não há informações disponíveis.",
			"sInfo": "_START_ até _END_ de _TOTAL_ linhas",
			"sInfoEmpty": "0 até 0 de 0 linhas",
			//"sInfoFiltered": "(filtrado para _MAX_ linhas)",
			"sInfoFiltered": "",
			"sInfoPostFix": "",
			"sSearch": "",
			"sUrl": "",
			"oPaginate": {
				"sFirst": 	 "Primeiro",
				"sPrevious": "Anterior",
				"sNext":     "Próximo",
				"sLast":     "Último"
			}
		},
		"aoColumns": aoColumnsDisponiveis,
		"fnPreDrawCallback": function( oSettings ) {
			$("#"+idDisponiveis+"_wrapper").css({"min-height": "0px"});
		},
		"fnDrawCallback": function ( oSettings ) {
			$(".addSelecionadosBtn").button({ icons: { primary: "ui-icon ui-icon-arrowthick-1-e"},text: false});
			$('#'+idDisponiveis).highlight('td','highlightEscuro','mouseover', 'mouseout');
			$('#'+idDisponiveis).highlight('tr','highlightEscuro','mouseover', 'mouseout');
		},
		"fnHeaderCallback":function(){
			$("#filtroesquerda .dataTables_filter").css({"float": "left"});
		},
		"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
			$(nRow).click(function(event) {
				if ( $(nRow).hasClass('row_selected') )
					$(nRow).removeClass('row_selected');
				else
					$(nRow).addClass('row_selected');
			});
			return nRow;
		},
		"sAjaxSource": "disciplinas",
		"fnServerData":function( sSource, aoData, fnCallback ) {
			$.ajax({ 
				"type": "GET",
				"contentType": "application/json; charset=utf-8",
				"dataType": "json",
				"url": sSource,
				"beforeSend": function(xhr){
					$("#"+idDisponiveis).block({message: "<img border='0' src='"+"img/ajax-loader.gif"+"'/> &nbsp;Buscando dados...",
						css: { 'border': '0px',
							'background': 'transparent',
							'color': 'white'
						} 
					});
				},
				"success": function(data){
					fnCallback({"aaData":data});
				},
				"complete":function(){
					$("#"+idDisponiveis).unblock();
					//highLight
				}
			});
		}
	});



	$('#'+idSelecionadas).dataTable({
		"sDom": 'l<"#filtroesquerda" f>rtip',
		"iDisplayLength": 7,
		"bStateSave": false,
		"bDeferRender": true,
		"bProcessing": false,
		"bJQueryUI" : false,
		"bFilter":true,
		"bLengthChange": false,
		"bSort": false,
		"bInfo": false,
		"bPaginate":false,
		"oLanguage": {
			"sProcessing": "Por favor, espere ...",
			"sLengthMenu": "Mostrar _MENU_ linhas",
			"sZeroRecords": "Não há informações disponíveis.",
			"sInfo": "_START_ até _END_ de _TOTAL_ linhas",
			"sInfoEmpty": "0 até 0 de 0 linhas",
			//"sInfoFiltered": "(filtrado para _MAX_ linhas)",
			"sInfoFiltered": "",
			"sInfoPostFix": "",
			"sSearch": "",
			"sUrl": "",
			"oPaginate": {
				"sFirst": 	 "Primeiro",
				"sPrevious": "Anterior",
				"sNext":     "Próximo",
				"sLast":     "Último"
			}
		},
		"aoColumns": aoColumnsSelecionados,
		"fnPreDrawCallback": function( oSettings ) {
			$("#"+idSelecionadas+"_wrapper").css({"min-height": "0px"});
		},
		"fnDrawCallback": function ( oSettings ) {
			$(".voltarDataGridBtn").button({icons: {primary: "ui-icon ui-icon-arrowthick-1-w"},text: false});
			$('#'+idSelecionadas).highlight('td','highlightEscuro','mouseover', 'mouseout');
			$('#'+idSelecionadas).highlight('tr','highlightEscuro','mouseover', 'mouseout');
		},
		"fnHeaderCallback":function(){
			$("#filtroesquerda .dataTables_filter").css({"float": "left"});
		},
		"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
			$(nRow).click(function(event) {
				if ( $(nRow).hasClass('row_selected') )
					$(nRow).removeClass('row_selected');
				else
					$(nRow).addClass('row_selected');
			});
			return nRow;
		}
	});
}

/*
 * funcao que adiciona um registro selecionado em uma datagrid para outra datagrid
 */
function addToSelecionados(event,idDataGridFrom, idDataGridTo , compareWith){
	var data = selecionarObjeto(event, idDataGridFrom);
	if(data!=null){
		var conteudo = $('#'+idDataGridTo).dataTable().fnGetData();
		var contem=false;
		for(var i=0; i<conteudo.length; i++){
			eval("if(conteudo[i]."+compareWith+" == data."+compareWith+"){contem=true; }");
		}
		if(!contem){
			$('#'+idDataGridTo).dataTable().fnAddData(data);
		}
	}
}

/*
 * funcao que constroi uma datagrid com uma listagem usando Bserverside
 * que utiliza consultas dinamicas no servidor
 * com filtro avancado
 */
function listServerSide(id, url, table, whereInicial, classe, arrString, encoded){
	try{
		/////////////////////////////////////filtro avancado///////////////////////
		$("#filtroAdicionarBtn").button({icons: {primary: "ui-icon-plusthick"}, text: false}).click(
				function(){
					var formulario = $("#filtroForm").formParams(false);
					if($('#filtroDataGrid').dataTable().fnGetData().length==0){
						delete formulario.eOu;
					}
					$('#filtroDataGrid').dataTable().fnAddData(formulario);
					$('#filtroDataGrid').dataTable().fnDraw();
					if($('#filtroDataGrid').dataTable().fnGetData().length>=1){
						$("#eOuField").show('slow');
					}
					$('#'+id).dataTable().fnCallBServerSearch();
				});
		$('#filtroDataGrid').dataTable({
				"sDom": '<"H" <"#filtroDataGrid_controle" > > t ',
				"bStateSave": false,
				"bDeferRender":true,
				"bProcessing":false,
				"bJQueryUI" : true,
				"bFilter":false,
				"bLengthChange":false,
				"bSort": false,
				"bInfo": false,
				"bPaginate":false,
				"bDestroy": true, // nao testado
				"oLanguage": {
					"sProcessing": "Por favor, espere ...",
					"sLengthMenu": "Mostrar _MENU_ linhas",
					"sZeroRecords": "Não há informações disponíveis.",
					"sInfo": "_START_ até _END_ de _TOTAL_ linhas",
					"sInfoEmpty": "0 até 0 de 0 linhas",
					//"sInfoFiltered": "(filtrado para _MAX_ linhas)", 			
					"sInfoFiltered": "",
					"sInfoPostFix": "",
					"sSearch": "Procurar",
					"sUrl": "",
					"oPaginate": {
						"sFirst": 	 "Primeiro",
						"sPrevious": "Anterior",
						"sNext":     "Próximo",
						"sLast":     "Último"
					}
				},
				"aoColumns": [
		                       {"sTitle": "-", "mDataProp": "eOu", "sWidth": "10px","sClass": "center", "bVisible": true, "sDefaultContent":"" },
		                       {"sTitle": "Campo", "mDataProp": "campo", "sWidth": "90px","sClass": "right", "bVisible": true, "sDefaultContent":"" },
		                       {"sTitle": "Restrição", "mDataProp": "restricao", "sWidth": "50px","bVisible": true,"sClass": "center", "sDefaultContent":"" },
		                       {"sTitle": "Valor", "mDataProp": "valor", "bVisible": true, "sDefaultContent":"" },
		                       {"sTitle": "Opções", "mDataProp": "htmlControl","bSortable": false, "bVisible": true, "sClass": "left","sWidth": "45px","sDefaultContent":"", 
			                    	   "fnRender": function ( oObj ) {
			                    		   return  "<button type=\"button\" id=\"deletarBtn_"+oObj.aData.id+"\"   class=\"deletarBtnfiltroDataGrid\" onclick=\"deletarDaTela(event,'filtroDataGrid');$('#"+id+"').dataTable().fnCallBServerSearch();\">Deletar</button>";
			                    	   }
		                       }
	                       ],
				"fnPreDrawCallback": function( oSettings ) {
					$("#"+id+"_wrapper").css({"min-height": "0px"});
				},
				"fnDrawCallback":function(){
					$(".editarBtnfiltroDataGrid").button({icons: {primary: "ui-icon-pencil"}, text: false});
					$(".editarBtnfiltroDataGrid").css({'width': '20px', 'height': '20px'});
					$(".deletarBtnfiltroDataGrid").button({icons: {primary: "ui-icon-close"}, text: false});
					$(".deletarBtnfiltroDataGrid").css({'width': '20px', 'height': '20px'});
					$(".magnifierGlassDataGridBtnfiltroDataGrid").button({icons: {primary: "ui-icon-search"}, text: false});
					$(".magnifierGlassDataGridBtnfiltroDataGrid").css({'width': '20px', 'height': '20px'});
					$('#'+id).highlight('td','highlightEscuro','mouseover', 'mouseout');
					$('#'+id).highlight('tr','highlightEscuro','mouseover', 'mouseout');
				},
				"fnRowCallback": function( nRow, aData, iDisplayIndex ) {

					$(nRow).click(function(event) {
						if ( $(nRow).hasClass('row_selected') )
							$(nRow).removeClass('row_selected');
						else
							$(nRow).addClass('row_selected');
					});
					return nRow;
				}
		}); 

		$('#filtroDataGrid').css({'width': '100%'});
		$('#filtroDataGrid_controle').append( 
				"<button type=\"button\" class=\"headerTextBtn\" onclick=\"multiDelete('filtroDataGrid',null);\" id=\"deletarMultiBtnfiltroDataGrid\">selecionados</button>"+
				"<button type=\"button\" class=\"headerTextBtn\" onclick=\"selectAll('filtroDataGrid');\" id=\"selectAllBtnfiltroDataGrid\">todos</button>"+
				"<button type=\"button\" class=\"headerTextBtn\" onclick=\"selectNone('filtroDataGrid');\" id=\"selectNoneBtnfiltroDataGrid\">nenhum</button>"
		);
		var filtroDeletarMultiBtn = $("#deletarMultiBtnfiltroDataGrid").button({ icons: { primary: "ui-icon ui-icon-closethick"},text: true});
		var filtroSelectAllBtn = $("#selectAllBtnfiltroDataGrid").button({ icons: { primary: "ui-icon ui-icon-carat-1-se"},text: true});
		var filtroSelectNoneBtn = $("#selectNoneBtnfiltroDataGrid").button({ icons: { primary: "ui-icon ui-icon-carat-1-ne"},text: true});
		
		//////////////////////////////////////////////////////////////////////////

		if(whereInicial=="" || whereInicial.length ==0 || whereInicial == undefined || whereInicial== " "){
			whereInicial = " where 1=1 ";
		}

		//trata o render de um para muitos
		var funcRenerIsList = function ( oObj) {
			eval("var lista = oObj.aData."+oObj.mDataProp+";");
			var str ="<ul>";
			for(var i =0; i< lista.length; i++){
				str +="<li>";
				eval("str +=lista[i]."+oObj.oSettings.aoColumns[oObj.iDataColumn].insideDataProp+";");
				str +="</li>";
			}
			str +="</ul>";
			return  str;
		};

		//recebe o arr de string
		var aoColumns = $.parseJSON(arrString);
		for(var i=0; i< aoColumns.length; i++){
			if(aoColumns[i].fnRender!=undefined){
				eval("var func = " + aoColumns[i].fnRender);
				aoColumns[i].fnRender = func;
			}
			if(aoColumns[i].isList!=undefined && aoColumns[i].isList){
				aoColumns[i].fnRender = funcRenerIsList;
			}
		}

		//cria a coluna de controle
		var possuiHtmlControl=false;
		for (var i = 0; i < aoColumns.length; i++) {
			if(aoColumns[i].mDataProp=="htmlControl"){
				possuiHtmlControl=true;
			}
		}
		if(!possuiHtmlControl){
			var htmlControl = {"sTitle": "Opções", "mDataProp": "htmlControl","bSortable": false, "bVisible": true, "sWidth": "90px","sDefaultContent":"", 
					"fnRender": function ( oObj ) {
						return  "<button type=\"button\" id=\"magnifierBtn_"+oObj.aData.id+"\"  class=\"magnifierGlassDataGridBtn"+id+"\" onclick=\"vizualizar()\" >Ver</button>"+
						"<button type=\"button\" id=\"editarBtn_"+oObj.aData.id+"\"  class=\"editarBtn"+id+"\" onclick=\"editar(event,'"+id+"','"+url+"','"+classe+"')\" >Editar</button>"+
						"<button type=\"button\" id=\"deletarBtn_"+oObj.aData.id+"\"  class=\"deletarBtn"+id+"\" onclick=\"deletarDoBanco('"+url+"',event,'"+id+"')\">Deletar</button>";
					}
			};
			aoColumns.push(htmlControl);
		}

		//opçoes da datatable
		var options = {
				//"sDom": 'TC<"clear"><"H"fr>t<"F"ip>S',
				"sDom": 'TRC<"clear">l<"H"fr>t<"F"ip>S', 
				"oTableTools": {
					"sSwfPath": "swf/datatables/copy_csv_xls_pdf.swf",
					"sRowSelect": "multi",
					"aButtons": [
					             {
					            	 "sExtends":    "text",
					            	 "sButtonText": "Filtros avançados",
					            	 "fnClick": function ( nButton, oConfig, oFlash ) {
					            		 $('#filtrosAvancados').toggle('slow');
					            		 $('#filtroDataGrid').dataTable().fnClearTable();
					            		 $('#'+id).dataTable().fnCallBServerSearch();
					            	 }
					             },
					             {
					            	 "sExtends":    "collection",
					            	 "sButtonText": "Selecionar",
					            	 "aButtons":    [ 
					            	                 {	"sExtends": "select_all", "sButtonText": "Selecionar todos" },
					            	                 {	"sExtends": "select_none", "sButtonText": "Selecionar nenhum" }
					            	                 ]
					             },
					             {
					            	 "sExtends":    "collection",
					            	 "sButtonText": "Opções",
					            	 "aButtons":    [
					            	                 {	"sExtends": "copy", "sButtonText": "Copiar para área de transferência" },
					            	                 {	"sExtends": "print", "sButtonText": "Imprimir" }
					            	                 ]
					             },
					             {
					            	 "sExtends":    "collection",
					            	 "sButtonText": "Salvar como",
					            	 "aButtons":    [ 
					            	                 { 	"sExtends": "pdf",
					            	                	 "sButtonText": "PDF", 
					            	                	 "mColumns": "visible",
					            	                	 "sPdfOrientation": "landscape",
					            	                	 "bHeader": true, 
					            	                	 "sTitle": "Ministério da Justiça SIGEN - Sistema de Gerenciamento de Ensino Nacional ",//+ table.split(".")[1].trim()
					            	                	 "sPdfMessage": "Gerado às " + new Date()
					            	                 },
					            	                 {   "sExtends": "csv", "sButtonText": "CSV","mColumns": "visible" ,"sTitle": "* "},
					            	                 {	"sExtends": "xls", "sButtonText": "Excel","mColumns": "visible","sTitle": "*"}//+table.split(".")[1].trim()
					            	                 ]
					             }

					             ]
				},
				"oColVis": {
					"buttonText": "&nbsp;⬇",
					"bRestore": true,
					"sAlign": "left"
				},
				"bProcessing": true,
				"bDestroy": true, // nao testado
				"bServerSide": true,
				"sServerMethod": "POST",
				"sAjaxDataProp": "aaData",
				"sAjaxSource": url,
				"aaSorting": [[ 2, "desc" ]],
				"bJQueryUI": true,
				"bDeferRender": true,
				"bPaginate": false,
//				"sPaginationType": "full_numbers",
				"oScroller": {
					"loadingIndicator": true
				},
				"sScrollY": "200px",
				"aoColumns": aoColumns,
				"oLanguage": {
					"sProcessing": "Por favor, espere ...",
					"sLengthMenu": "Mostrar _MENU_ linhas",
					"sZeroRecords": "Não há informações disponíveis.",
					"sInfo": "_START_ até _END_ de _TOTAL_ linhas",
					"sInfoEmpty": "0 até 0 de 0 linhas",
					//"sInfoFiltered": "(filtrado para _MAX_ linhas)",
					"sInfoFiltered": "",
					"sInfoPostFix": "",
					"sSearch": "Procurar",
					"sUrl": "",
					"oPaginate": {
						"sFirst": 	 "Primeiro",
						"sPrevious": "Anterior",
						"sNext":     "Próximo",
						"sLast":     "Último"
					}
				},
				"fnServerData": function ( sSource, aoData, fnCallback ) {

					var whereAdicional = "";
					var valor="";
					var filtros = $('#filtroDataGrid').dataTable().fnGetData();
					if(filtros != undefined && filtros.length>0){
						if(filtros[0].eOu ==null || filtros[0].eOu ==undefined || filtros[0].eOu ==""){
							filtros[0].eOu = " and ";
						}
					}
					for(var i=0; i<filtros.length; i++){
						var filtro = filtros[i];

						for(var k =0; k<aoColumns.length;k++){
							var optionValue ="";
							if(aoColumns[k].isList!=undefined && aoColumns[k].isList){
								optionValue = aoColumns[k].mDataProp+"."+aoColumns[k].insideDataProp;
							}else{
								optionValue = "o."+aoColumns[k].mDataProp;
							}
							if(filtro.campo==optionValue){
								if(aoColumns[k].sType=="numeric"){
									valor=filtro.valor; 
									whereAdicional += filtro.eOu + "   "+  filtro.campo + " "+ filtro.restricao +" "+valor;
								}else if(aoColumns[k].sType=="date" ){
									valor= "'"+filtro.valor+"'"; 
									whereAdicional += filtro.eOu + " cast( "+  filtro.campo + " as date)"+ filtro.restricao +" cast( "+valor + " as date)";
								}else{
									if(filtro.restricao=="="){
										valor="'"+filtro.valor.toLowerCase()+"'"; 
									} else if (filtro.restricao=="like"){
										valor=" '%"+filtro.valor.toLowerCase()+"%' "; 
									}
									whereAdicional += filtro.eOu + " lower(cast( "+  filtro.campo + " as string))"+ filtro.restricao +" "+valor;
								}
							}
						}
					}

					for(var i=0; i<aoColumns.length; i++){
						if(aoColumns[i].columName!=undefined || aoColumns[i].columName!=null){
							eval('aoData.push( { "name": "columName_'+i+'", "value": "'+aoColumns[i].columName+'" } )');
						}
						if(aoColumns[i].isList!=undefined || aoColumns[i].isList!=null){
							eval('aoData.push( { "name": "isList_'+i+'", "value": "'+aoColumns[i].isList+'" } )');
						}else{
							eval('aoData.push( { "name": "isList_'+i+'", "value": "false" } )');
						}
						if(aoColumns[i].insideDataProp!=undefined || aoColumns[i].insideDataProp!=null){
							eval('aoData.push( { "name": "insideDataProp_'+i+'", "value": "'+aoColumns[i].insideDataProp+'" } )');
						}else{
							eval('aoData.push( { "name": "insideDataProp_'+i+'", "value": "" } )');
						}
					}
					aoData.push( { "name": "table", "value": table } );
					aoData.push( { "name": "whereInicial", "value": whereInicial } );
					aoData.push( { "name": "whereAdicional", "value": whereAdicional } );
					aoData.push( { "name": "class", "value": classe } );
					aoData.push( { "name": "encoded", "value": encoded } );
					//urlencode ssearch
//					for(var k=0; k<aoData.length; k++){
//					if(aoData[k].name == "sSearch"){
//					aoData[k].value=$.URLEncode(aoData[k].value).replaceAll("+", " ");
//					}
//					}

					$.ajax( {
						"dataType": 'json',
						"contentType": "application/json; charset=utf-8",
						"type": "POST",
						"beforeSend": function(xhr,settings){
							settings.data = $.toJSON(aoData);
						},
						"processData": false,
						"url": sSource,
						"success": fnCallback
					} );
				},
//				'fnInitComplete' : function () {
//				$("table").append('<tfoot></tfoot>');
//				$("thead tr").clone().appendTo($("tfoot")).addClass("filter") ;
//				var datatable = $('#'+id).dataTable();
//				datatable.columnFilter();
//				},
				"fnPreDrawCallback": function( oSettings ) {
					$("#"+id+"_wrapper").css({"min-height": "0px"});
				},
				"fnDrawCallback":function(o){
					$(".editarBtn"+id).button({icons: {primary: "ui-icon-pencil"}, text: false});
					$(".editarBtn"+id).css({'width': '20px', 'height': '20px'});
					$(".deletarBtn"+id).button({icons: {primary: "ui-icon-close"}, text: false});
					$(".deletarBtn"+id).css({'width': '20px', 'height': '20px'});
					$(".printBtn"+id).button({icons: {primary: "ui-icon-print"}, text: false});
					$(".printBtn"+id).css({'width': '20px', 'height': '20px'});
					$(".checkBtn"+id).button({icons: {primary: "ui-icon-check"}, text: false});
					$(".checkBtn"+id).css({'width': '20px', 'height': '20px'});
					$(".magnifierGlassDataGridBtn"+id).button({icons: {primary: "ui-icon-search"}, text: false});
					$(".magnifierGlassDataGridBtn"+id).css({'width': '20px', 'height': '20px'});
					$('#'+id).highlight('td','highlightEscuro','mouseover', 'mouseout');
					$('#'+id).highlight('tr','highlightEscuro','mouseover', 'mouseout');
					/* Position the ColVis button as needed */
					var nColVis = $('div.ColVis', o.nTableWrapper)[0];
					nColVis.style.width = "15px";
					nColVis.style.top = "34px";
					nColVis.style.height = "22px";
				},
				"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
					$(nRow).click(function(event) {
						if ( $(nRow).hasClass('row_selected') )
							$(nRow).removeClass('row_selected');
						else
							$(nRow).addClass('row_selected');
					});
					return nRow;
				}
		};
		options.aoColumns=aoColumns;




		$('#'+id).dataTable(options);//here

		$('#'+id).css({'width': '100%'});

		//set delay	
		$('#'+id).dataTable().fnSetFilteringDelay(500);//250ms

		/////////////////campos do filtro avancado ///////////////

		$('#campo').append($("<option></option>").attr("value","").text("--------"));
		for(var i =0; i<aoColumns.length;i++){
			if(aoColumns[i].isList!=undefined && aoColumns[i].isList){
				$('#campo').append($("<option></option>").attr("value",aoColumns[i].mDataProp+"."+aoColumns[i].insideDataProp).text(aoColumns[i].sTitle)); 
			}else{
				$('#campo').append($("<option></option>").attr("value","o."+aoColumns[i].mDataProp).text(aoColumns[i].sTitle)); 
			}
		}

		$('#campo').change( function(){
			for(var i =0; i<aoColumns.length;i++){
				if(aoColumns[i].mDataProp=="htmlControl"){
					continue;
				}
				var optionValue ="";
				if(aoColumns[i].isList!=undefined && aoColumns[i].isList){
					optionValue = aoColumns[i].mDataProp+"."+aoColumns[i].insideDataProp;
				}else{
					optionValue = "o."+aoColumns[i].mDataProp;
				}
				if($('#campo').val()==optionValue){
					//campo select restricao
					$('#restricao').find('option').remove().end();
					if(aoColumns[i].sType=="numeric" || aoColumns[i].sType=="date" ){
						$('#restricao').append($("<option></option>").attr("value","=").text("igual a"));
						$('#restricao').append($("<option></option>").attr("value",">=").text("maior que ou igual a"));
						$('#restricao').append($("<option></option>").attr("value","<=").text("menor que ou igual a"));
					}else{
						$('#restricao').append($("<option></option>").attr("value","like").text("parecido com"));
						$('#restricao').append($("<option></option>").attr("value","=").text("igual a"));
					}

					//campo valor
					$('#valorField').html('');
					if(aoColumns[i].sType=="numeric"){
						$('#valorField').html('<label for="valor" style="margin-right:10px">Valor:</label><input type="text" name="valor" id="valor" class="field validate[required number]" />');
					}else if(aoColumns[i].sType=="date" ){
						$('#valorField').html('<label for="valor" style="margin-right:10px">Valor:</label><input type="text" id="valor" name="valor" class="field validate[required date]" >');
						datePicker("valor");
					}else{
						$('#valorField').html('<label for="valor" style="margin-right:10px">Valor:</label><input type="text" name="valor" id="valor" class="field validate[required]" />');
					}
				}
			}
		});
		/////////////////////////////////////////////////////
	}catch(e){
		showDialog("Erro",e.message); 
		erro = e;
	}
}


/*
 * funcao que constroi uma datagrid com uma listagem usando Bserverside
 * que utiliza consultas dinamicas no servidor
 * sem filtro avancado
 */
function listServerSideSemFiltro(id, url, table, whereInicial, classe, arrString, encoded){
	try{
		if(whereInicial=="" || whereInicial.length ==0 || whereInicial == undefined || whereInicial== " "){
			whereInicial = " where 1=1 ";
		}
		//trata o render de um para muitos
		var funcRenerIsList = function ( oObj) {
			eval("var lista = oObj.aData."+oObj.mDataProp+";");
			var str ="<ul>";
			for(var i =0; i< lista.length; i++){
				str +="<li>";
				eval("str +=lista[i]."+oObj.oSettings.aoColumns[oObj.iDataColumn].insideDataProp+";");
				str +="</li>";
			}
			str +="</ul>";
			return  str;
		};
		//recebe o arr de string
		var aoColumns = $.parseJSON(arrString);
		for(var i=0; i< aoColumns.length; i++){
			if(aoColumns[i].fnRender!=undefined){
				eval("var func = " + aoColumns[i].fnRender);
				aoColumns[i].fnRender = func;
			}
			if(aoColumns[i].isList!=undefined && aoColumns[i].isList){
				aoColumns[i].fnRender = funcRenerIsList;
			}
		}
		//opçoes da datatable
		var options = {
				//"sDom": 'TC<"clear"><"H"fr>t<"F"ip>S',
				"sDom": 'RC<"clear">l<"H"fr>t<"F"ip>S', 
				"oColVis": {
					"buttonText": "&nbsp;⬇",
					"bRestore": true,
					"sAlign": "left"
				},
				"bProcessing": true,
				"bDestroy": true, // nao testado
				"bServerSide": true,
				"sServerMethod": "POST",
				"sAjaxDataProp": "aaData",
				"sAjaxSource": url,
				"aaSorting": [[ 2, "desc" ]],
				"bJQueryUI": true,
				"bDeferRender": true,
				"bPaginate": false,
//				"sPaginationType": "full_numbers",
				"oScroller": {
					"loadingIndicator": true
				},
				"sScrollY": "200px",
				"aoColumns": aoColumns,
				"oLanguage": {
					"sProcessing": "Por favor, espere ...",
					"sLengthMenu": "Mostrar _MENU_ linhas",
					"sZeroRecords": "Não há informações disponíveis.",
					"sInfo": "_START_ até _END_ de _TOTAL_ linhas",
					"sInfoEmpty": "0 até 0 de 0 linhas",
					//"sInfoFiltered": "(filtrado para _MAX_ linhas)",
					"sInfoFiltered": "",
					"sInfoPostFix": "",
					"sSearch": "Procurar",
					"sUrl": "",
					"oPaginate": {
						"sFirst": 	 "Primeiro",
						"sPrevious": "Anterior",
						"sNext":     "Próximo",
						"sLast":     "Último"
					}
				},
				"fnServerData": function ( sSource, aoData, fnCallback ) {
					for(var i=0; i<aoColumns.length; i++){
						if(aoColumns[i].columName!=undefined || aoColumns[i].columName!=null){
							eval('aoData.push( { "name": "columName_'+i+'", "value": "'+aoColumns[i].columName+'" } )');
						}
						if(aoColumns[i].isList!=undefined || aoColumns[i].isList!=null){
							eval('aoData.push( { "name": "isList_'+i+'", "value": "'+aoColumns[i].isList+'" } )');
						}else{
							eval('aoData.push( { "name": "isList_'+i+'", "value": "false" } )');
						}
						if(aoColumns[i].insideDataProp!=undefined || aoColumns[i].insideDataProp!=null){
							eval('aoData.push( { "name": "insideDataProp_'+i+'", "value": "'+aoColumns[i].insideDataProp+'" } )');
						}else{
							eval('aoData.push( { "name": "insideDataProp_'+i+'", "value": "" } )');
						}
					}
					aoData.push( { "name": "table", "value": table } );
					aoData.push( { "name": "whereInicial", "value": whereInicial } );
					aoData.push( { "name": "whereAdicional", "value": "" } );
					aoData.push( { "name": "class", "value": classe } );
					aoData.push( { "name": "encoded", "value": encoded } );
					$.ajax( {
						"dataType": 'json',
						"contentType": "application/json; charset=utf-8",
						"type": "POST",
						"beforeSend": function(xhr,settings){
							settings.data = $.toJSON(aoData);
						},
						"processData": false,
						"url": sSource,
						"success": fnCallback
					} );
				},
				"fnPreDrawCallback": function( oSettings ) {
					$("#"+id+"_wrapper").css({"min-height": "0px"});
				},
				"fnDrawCallback":function(o){
					$(".editarBtn"+id).button({icons: {primary: "ui-icon-pencil"}, text: false});
					$(".editarBtn"+id).css({'width': '20px', 'height': '20px'});
					$(".deletarBtn"+id).button({icons: {primary: "ui-icon-close"}, text: false});
					$(".deletarBtn"+id).css({'width': '20px', 'height': '20px'});
					$(".printBtn"+id).button({icons: {primary: "ui-icon-print"}, text: false});
					$(".printBtn"+id).css({'width': '20px', 'height': '20px'});
					$(".checkBtn"+id).button({icons: {primary: "ui-icon-check"}, text: false});
					$(".checkBtn"+id).css({'width': '20px', 'height': '20px'});
					$(".magnifierGlassDataGridBtn"+id).button({icons: {primary: "ui-icon-search"}, text: false});
					$(".magnifierGlassDataGridBtn"+id).css({'width': '20px', 'height': '20px'});
					$('#'+id).highlight('td','highlightEscuro','mouseover', 'mouseout');
					$('#'+id).highlight('tr','highlightEscuro','mouseover', 'mouseout');
					/* Position the ColVis button as needed */
					var nColVis = $('div.ColVis', o.nTableWrapper)[0];
					nColVis.style.width = "15px";
					nColVis.style.top = "34px";
					nColVis.style.height = "22px";
				},
				"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
					$(nRow).click(function(event) {
						if ( $(nRow).hasClass('row_selected') )
							$(nRow).removeClass('row_selected');
						else
							$(nRow).addClass('row_selected');
					});
					return nRow;
				}
		};
		options.aoColumns=aoColumns;
		
		$('#'+id).dataTable(options);//here
		
		$('#'+id).css({'width': '100%'});
		
		//set delay	
		$('#'+id).dataTable().fnSetFilteringDelay(500);//250ms
		
	}catch(e){
		showDialog("Erro",e.message); 
		erro = e;
	}
}

function multiSelectBServerSideDataGrid(idDisponiveis, urlDisponiveis, tableDisponiveis, whereDisponiveis, classeDisponiveis, aoColumnsDisponiveisStr, idSelecionadas,aoColumnsSelecionadosStr,comararCom){

	var htmlControlDisponiveis = {"sTitle": "Opções", "mDataProp": "htmlControl","bSortable": false, "bVisible": true, "sWidth": "45px","sDefaultContent":"", 
			"fnRender": function ( oObj ) {
				return  "<button type=\"button\" id=\"addBtn_"+oObj.aData.id+"\"  class=\"addSelecionadosBtn\" onclick=\"addToSelecionados(event,'"+idDisponiveis+"','"+idSelecionadas+"','"+comararCom+"');\" >Passar para direita</button>";
			}
	};
	var htmlControlSelecionadas = {"sTitle": "Opções", "mDataProp": "htmlControl","bSortable": false, "bVisible": true, "sWidth": "45px","sDefaultContent":"", 
			"fnRender": function ( oObj ) {
				return  "<button type=\"button\" id=\"removerBtn_"+oObj.aData.id+"\"  class=\"voltarDataGridBtn\" onclick=\"deletarDaTela(event,'"+idSelecionadas+"');\">Deletar</button>";
			}
	};


	var aoColumnsDisponiveis = $.parseJSON(aoColumnsDisponiveisStr);

	for(var i=0; i< aoColumnsDisponiveis.length; i++){
		if(aoColumnsDisponiveis[i].fnRender!=undefined){
			eval("var func = " + aoColumnsDisponiveis[i].fnRender);
			aoColumnsDisponiveis[i].fnRender = func;
		}
	}

	var aoColumnsSelecionados = $.parseJSON(aoColumnsSelecionadosStr);
	for(var i=0; i< aoColumnsSelecionados.length; i++){
		if(aoColumnsSelecionados[i].fnRender!=undefined){
			eval("var func = " + aoColumnsSelecionados[i].fnRender);
			aoColumnsSelecionados[i].fnRender = func;
		}
	}

	aoColumnsDisponiveis.push(htmlControlDisponiveis);
	aoColumnsSelecionados.push(htmlControlSelecionadas);

	$('#'+idDisponiveis).dataTable({
		"sDom": 'l<"#filtroesquerda" f>rtip',
		"iDisplayLength": 7,
		"bStateSave": false,
		"bDeferRender": true,
		"bProcessing": false,
		"bJQueryUI" : false,
		"bFilter":true,
		"bLengthChange": false,
		"bInfo": false,
		"bPaginate":true,
		"oLanguage": {
			"sProcessing": "Por favor, espere ...",
			"sLengthMenu": "Mostrar _MENU_ linhas",
			"sZeroRecords": "Não há informações disponíveis.",
			"sInfo": "_START_ até _END_ de _TOTAL_ linhas",
			"sInfoEmpty": "0 até 0 de 0 linhas",
			//"sInfoFiltered": "(filtrado para _MAX_ linhas)",
			"sInfoFiltered": "",
			"sInfoPostFix": "",
			"sSearch": "",
			"sUrl": "",
			"oPaginate": {
				"sFirst": 	 "",
				"sPrevious": "",
				"sNext":     "",
				"sLast":     ""
			}
		},
		"aoColumns": aoColumnsDisponiveis,
		"fnPreDrawCallback": function( oSettings ) {
			$("#"+idDisponiveis+"_wrapper").css({"min-height": "0px"});
		},
		"fnDrawCallback": function ( oSettings ) {
			$(".addSelecionadosBtn").button({ icons: { primary: "ui-icon ui-icon-arrowthick-1-e"},text: false});
			$('#'+idDisponiveis).highlight('td','highlightEscuro','mouseover', 'mouseout');
			$('#'+idDisponiveis).highlight('tr','highlightEscuro','mouseover', 'mouseout');
		},
		"fnHeaderCallback":function(){
			$("#filtroesquerda .dataTables_filter").css({"float": "left"});
		},
		"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
			$(nRow).click(function(event) {
				if ( $(nRow).hasClass('row_selected') )
					$(nRow).removeClass('row_selected');
				else
					$(nRow).addClass('row_selected');
			});
			return nRow;
		},
		"bServerSide": true,
		"fnServerData": function ( sSource, aoData, fnCallback ) {
			for(var i=0; i<aoColumnsDisponiveis.length; i++){
				if(aoColumnsDisponiveis[i].columName!=undefined)
					eval('aoData.push( { "name": "columName_'+i+'", "value": "'+aoColumnsDisponiveis[i].columName+'" } )');
			}
			aoData.push( { "name": "table", "value": tableDisponiveis } );
			aoData.push( { "name": "where", "value": whereDisponiveis } );
			aoData.push( { "name": "class", "value": classeDisponiveis } );
			aoDataTemp = aoData;			
			$.ajax( {
				"dataType": 'json',
				"type": "GET",
				"url": sSource,
				"data": aoData,
				"success": fnCallback
			} );
		},
		"sAjaxDataProp": "aaData",
		"sAjaxSource": urlDisponiveis
//		"aaSorting": [[ 2, "desc" ]]
	});

	//set delay	
	$('#'+idDisponiveis).dataTable().fnSetFilteringDelay(500);//250ms



	$('#'+idSelecionadas).dataTable({
		"sDom": 'l<"#filtroesquerda" f>rtip',
		"iDisplayLength": 7,
		"bStateSave": false,
		"bDeferRender": true,
		"bProcessing": false,
		"bJQueryUI" : false,
		"bFilter":true,
		"bLengthChange": false,
		"bSort": false,
		"bInfo": false,
		"bPaginate":true,
		"oLanguage": {
			"sProcessing": "Por favor, espere ...",
			"sLengthMenu": "Mostrar _MENU_ linhas",
			"sZeroRecords": "Não há informações disponíveis.",
			"sInfo": "_START_ até _END_ de _TOTAL_ linhas",
			"sInfoEmpty": "0 até 0 de 0 linhas",
			//"sInfoFiltered": "(filtrado para _MAX_ linhas)", 							
			"sInfoFiltered": "",
			"sInfoPostFix": "",
			"sSearch": "",
			"sUrl": "",
			"oPaginate": {
				"sFirst": 	 "",
				"sPrevious": "",
				"sNext":     "",
				"sLast":     ""
			}
		},
		"aoColumns": aoColumnsSelecionados,
		"fnPreDrawCallback": function( oSettings ) {
			$("#"+idSelecionadas+"_wrapper").css({"min-height": "0px"});
		},
		"fnDrawCallback": function ( oSettings ) {
			$(".voltarDataGridBtn").button({icons: {primary: "ui-icon ui-icon-arrowthick-1-w"},text: false});
			$('#'+idSelecionadas).highlight('td','highlightEscuro','mouseover', 'mouseout');
			$('#'+idSelecionadas).highlight('tr','highlightEscuro','mouseover', 'mouseout');
		},
		"fnHeaderCallback":function(){
			$("#filtroesquerda .dataTables_filter").css({"float": "left"});
		},
		"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
			$(nRow).click(function(event) {
				if ( $(nRow).hasClass('row_selected') )
					$(nRow).removeClass('row_selected');
				else
					$(nRow).addClass('row_selected');
			});
			return nRow;
		}
	});
}
